package main

import (
	"context"
	"fmt"
	"go_rpc/grpc_stream/proto"
	"google.golang.org/grpc"
	"sync"
	"time"
)

func main() {
	conn, err := grpc.Dial("localhost:50052", grpc.WithInsecure())
	if err != nil {
		fmt.Println("异常:", err.Error())
		panic(err)
	}
	defer conn.Close()
	// 服务端流模式
	c := proto.NewGreeterClient(conn)
	stream, _ := c.GetStream(context.Background(), &proto.StreamReqData{Data: "袁鹏越"})
	for {
		res, err := stream.Recv()
		if err != nil {
			fmt.Println("异常:", err.Error())
			break
		}
		fmt.Println("res:", res.Data)
	}

	// 客户端流模式
	putS, _ := c.PostStream(context.Background())
	i := 0
	for {
		i++
		putS.Send(&proto.StreamReqData{Data: fmt.Sprintf("袁鹏越%d", i)})
		time.Sleep(time.Second)
		if i > 10 {
			break
		}
	}

	// 双向流模式
	allS, _ := c.AllStream(context.Background())
	wg := sync.WaitGroup{}
	wg.Add(2)
	go func() {
		defer wg.Done()
		for {
			data, _ := allS.Recv()
			fmt.Printf("收到客户端消息: %v", data)

		}
	}()

	go func() {
		defer wg.Done()
		for {
			_ = allS.Send(&proto.StreamReqData{Data: "我是客户端咯"})
			time.Sleep(time.Second)
		}
	}()
	wg.Wait()

}
